package edu.ynu.hhy.architectureclass.Scheduler;

import edu.ynu.hhy.architectureclass.entity.CameraData;
import edu.ynu.hhy.architectureclass.entity.Device;
import edu.ynu.hhy.architectureclass.entity.SensorData;
import edu.ynu.hhy.architectureclass.service.CameraDataService;
import edu.ynu.hhy.architectureclass.service.DeviceService;
import edu.ynu.hhy.architectureclass.service.SensorDataService;
import edu.ynu.hhy.architectureclass.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DeviceDataScheduler {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private CameraDataService cameraDataService;

    @Autowired
    private SensorDataService sensorDataService;

    @Autowired
    private TokenService tokenService;


    @Scheduled(fixedRate = 1200000)
    public void fetchAndSaveDeviceData() {
        // 获取所有设备
        List<Device> devices = deviceService.getAll();

        for (Device device : devices) {
            if ("camera".equals(device.getCategory())) {
                // 处理摄像头设备
                fetchAndSaveCameraData(device);
            } else if ("sensor".equals(device.getCategory())) {
                // 处理传感器设备
                fetchAndSaveSensorData(device);
            }
        }
    }

    private void fetchAndSaveCameraData(Device device) {
        String accessToken = tokenService.getYsToken(); // 获取萤石 API 的访问令牌
        if (accessToken != null) {
            // 获取摄像头抓拍图片并保存数据
            CameraData cameraData = cameraDataService.captureAndSaveCameraImage(device.getSerialNumber(), accessToken);
            if (cameraData != null) {
                System.out.println("Camera data saved: " + cameraData.getPicUrl());
            } else {
                System.out.println("Failed to fetch camera data for device: " + device.getSerialNumber());
            }
        } else {
            System.out.println("Failed to get access token for camera device: " + device.getSerialNumber());
        }
    }

    private void fetchAndSaveSensorData(Device device) {
        List<SensorData> sensorDataList = sensorDataService.getSensorData();

        if (sensorDataList != null && !sensorDataList.isEmpty()) {
            for (SensorData sensorData : sensorDataList) {
                sensorData.setDevice(device); // 关联设备
                sensorDataService.saveSensorData(sensorData); // 保存传感器数据
                System.out.println("Sensor data saved: " + sensorData.getValue());
            }
        } else {
            System.out.println("No sensor data fetched for device: " + device.getSerialNumber());
        }
    }
}